package com.hs.egova.config;

import com.hs.egova.hibernate.HibernateInteceptor;
import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.PropertySource;
import org.springframework.core.env.Environment;
import org.springframework.orm.hibernate5.HibernateTransactionManager;
import org.springframework.orm.hibernate5.LocalSessionFactoryBean;
import org.springframework.transaction.annotation.EnableTransactionManagement;

import javax.sql.DataSource;
import java.util.Properties;

/**
 * @author husheng
 * @version v1.0
 * @date 2021/7/26 16:08
 * @email husheng@egova.com.cn
 */
@Configuration
@EnableTransactionManagement
@ComponentScan("com.hs.egova")
@PropertySource(value = {"classpath:application.yml"})
public class HibernateConfig {
    @Autowired
    Environment environment;
    @Autowired
    DataSource dataSource;

    @Bean
    public LocalSessionFactoryBean sessionFactory() {
        LocalSessionFactoryBean sessionFactory = new LocalSessionFactoryBean();
        sessionFactory.setDataSource(dataSource);
        sessionFactory.setPackagesToScan(new String[] {"com.hs.egova.mapping"});
        sessionFactory.setEntityInterceptor(new HibernateInteceptor());
        sessionFactory.setHibernateProperties(hibernateProperties());
        return sessionFactory;
    }

    private Properties hibernateProperties() {
        Properties properties = new Properties();
        properties.put("hibernate.dialect", environment.getRequiredProperty("hibernate.dialect"));
        properties.put("hibernate.show_sql", environment.getRequiredProperty("hibernate.show_sql"));
        properties.put("hibernate.format_sql", environment.getRequiredProperty("hibernate.format_sql"));
        properties.put("hibernate.connection.isolation", "2");
        properties.put("hibernate.jdbc.use_streams_for_binary", "true");
        properties.put("hibernate.connection.release_mode", "after_transaction");
        return properties;
    }

    /**
     * 事务管理
     * @param sf
     * @return
     */
    @Bean
    @Autowired
    public HibernateTransactionManager transactionManager(SessionFactory sf) {
        HibernateTransactionManager txManager = new HibernateTransactionManager();
        txManager.setSessionFactory(sf);
        return txManager;
    }
}
